import {defineStore} from "pinia";

// 地址标签接口
export interface AddressTag {
    id: string;
    name: string;
    color: string;
    symbol: string;
    order: number;
}

// 地址分类接口
export interface AddressCategory {
    id: string;
    name: string;
    order: number;
}

// 地址接口
export interface Address {
    uid: string;
    title: string;
    address: string;
    point: any; // BMapGL.Point
    status: string;
    categoryId: string;
    addTime: string;
}

// 搜索结果接口
export interface SearchResult {
    title: string;
    address: string;
    point: any; // BMapGL.Point
    uid: string;
    index: number;
}

// 主要的 store
export const useMapStore = defineStore("map", {
    state: () => ({
        // Tab 状态
        activeTab: "search" as "list" | "search" | "settings",
        isLeftPanelCollapsed: false,

        // 地址数据
        addressList: [] as Address[],
        addressTags: [
            {id: "unchecked", name: "未打卡", color: "#ff6b6b", symbol: "O", order: 0},
            {id: "checked", name: "已打卡", color: "#51cf66", symbol: "C", order: 1},
        ] as AddressTag[],
        addressCategories: [{id: "default", name: "默认分类", order: 0}] as AddressCategory[],

        // 搜索状态
        searchKeyword: "",
        searchResults: [] as SearchResult[],
        isSearching: false,
        selectedSearchResultIndex: -1,
        selectedAddresses: [] as string[],
        listSearchKeyword: "",

        // 筛选状态
        selectedCategoryFilter: "all" as string,
        selectedTagFilter: "all" as string,

        // 默认添加设置
        defaultCategoryId: "default" as string,
        defaultTagId: "unchecked" as string,

        // 地图状态
        map: null as any,
        searchMarkers: [] as any[],
        addressMarkers: [] as any[],
    }),

    getters: {
        // 过滤后的地址列表
        filteredAddressList: state => {
            let filtered = state.addressList;

            // 按分类筛选
            if (state.selectedCategoryFilter !== "all") {
                filtered = filtered.filter(address => address.categoryId === state.selectedCategoryFilter);
            }

            // 按标签筛选
            if (state.selectedTagFilter !== "all") {
                filtered = filtered.filter(address => address.status === state.selectedTagFilter);
            }

            // 按关键词搜索
            if (state.listSearchKeyword.trim()) {
                const keyword = state.listSearchKeyword.trim();
                filtered = filtered.filter(address => {
                    return (
                        address.title.includes(keyword) ||
                        address.address.includes(keyword) ||
                        state.addressTags.find(tag => tag.id === address.status)?.name.includes(keyword) ||
                        state.addressCategories.find(cat => cat.id === address.categoryId)?.name.includes(keyword)
                    );
                });
            }

            return filtered;
        },

        // 获取标签名称
        getTagName: state => (tagId: string) => {
            const tag = state.addressTags.find(t => t.id === tagId);
            return tag ? tag.name : tagId;
        },

        // 获取分类名称
        getCategoryName: state => (categoryId: string) => {
            const category = state.addressCategories.find(c => c.id === categoryId);
            return category ? category.name : "默认分类";
        },
    },

    actions: {
        // Tab 切换
        setActiveTab(tab: "list" | "search" | "settings") {
            this.activeTab = tab;
        },

        // 切换左侧面板
        toggleLeftPanel() {
            this.isLeftPanelCollapsed = !this.isLeftPanelCollapsed;
            // 保存面板状态
            this.saveUIState();
        },

        // 保存UI状态
        saveUIState() {
            try {
                const uiState = {
                    isLeftPanelCollapsed: this.isLeftPanelCollapsed,
                };
                focusany.dbStorage.setItem(UI_STATE_STORAGE_KEY, uiState);
            } catch (error) {
                console.error("保存UI状态失败:", error);
            }
        },

        // 加载UI状态
        loadUIState() {
            try {
                const uiState = focusany.dbStorage.getItem(UI_STATE_STORAGE_KEY);
                if (uiState && typeof uiState === "object") {
                    if (typeof uiState.isLeftPanelCollapsed === "boolean") {
                        this.isLeftPanelCollapsed = uiState.isLeftPanelCollapsed;
                    }
                }
            } catch (error) {
                console.error("加载UI状态失败:", error);
            }
        },

        // 设置搜索关键词
        setSearchKeyword(keyword: string) {
            this.searchKeyword = keyword;
        },

        // 设置列表搜索关键词
        setListSearchKeyword(keyword: string) {
            this.listSearchKeyword = keyword;
        },

        // 设置分类筛选
        setCategoryFilter(categoryId: string) {
            this.selectedCategoryFilter = categoryId;
        },

        // 设置标签筛选
        setTagFilter(tagId: string) {
            this.selectedTagFilter = tagId;
        },

        // 设置默认分类
        setDefaultCategory(categoryId: string) {
            this.defaultCategoryId = categoryId;
        },

        // 设置默认标签
        setDefaultTag(tagId: string) {
            this.defaultTagId = tagId;
        },
    },
});

// 存储键
export const STORAGE_KEY = "map_marker_addresses";
export const TAGS_STORAGE_KEY = "map_marker_tags";
export const CATEGORIES_STORAGE_KEY = "map_marker_categories";
export const UI_STATE_STORAGE_KEY = "map_marker_ui_state";

// 上海市中心坐标
export const SHANGHAI_CENTER = {lng: 121.4737, lat: 31.2304};
